package by.averianov.discounta.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.stereotype.Repository;

import by.averianov.discounta.dataaccess.PriceBookDao;
import by.averianov.discounta.datamodel.PriceBook;

@Repository
public class PriceBookDaoImpl extends AbstractDaoImpl<Long, PriceBook> implements PriceBookDao {

	protected PriceBookDaoImpl() {
		super(PriceBook.class);
	}

	@Override
	public List<PriceBook> getAllPriceBook(SingularAttribute<PriceBook, ?> attr, boolean ascending,	int startRecord, int pageSize) {
		CriteriaBuilder cb = getEm().getCriteriaBuilder();

		CriteriaQuery<PriceBook> criteria = cb.createQuery(PriceBook.class);
		Root<PriceBook> root = criteria.from(PriceBook.class);

		criteria.select(root);
		criteria.orderBy(new OrderImpl(root.get(attr), ascending));
		TypedQuery<PriceBook> query = getEm().createQuery(criteria);
		query.setFirstResult(startRecord);
		query.setMaxResults(pageSize);

		List<PriceBook> results = query.getResultList();
		return results;
	}

}
